// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DictionaryService.cs" company="Open Trader">
//   Copyright (c) David Denis (david.denis@systemathics.com)
// </copyright>
// <summary>
//   |  Open Trader - The Open Source Systematic Trading Platform
//   |
//   |  This program is free software: you can redistribute it and/or modify
//   |  it under the terms of the GNU General Public License as published by
//   |  the Free Software Foundation, either version 2 of the License, or
//   |  (at your option) any later version.
//   |
//   |  This program is distributed in the hope that it will be useful,
//   |  but WITHOUT ANY WARRANTY; without even the implied warranty of
//   |  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   |  GNU General Public License for more details.
//   |
//   |  You should have received a copy of the GNU General Public License
//   |  along with this program.  If not, see http://www.gnu.org/licenses
//   |
//   |  Up to date informations about Open Trader can be found at :
//   |    http://opentrader.org
//   |    http://opentrader.codeplex.com
//   |
//   |  For professional services, please visit us at :
//   |    http://www.systemathics.com
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Org.OpenTrader.Framework.Forge
{
    #region Usings

    using System;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Reflection;

    using Org.OpenTrader.Framework.Enums;
    using Org.OpenTrader.Framework.Events;
    using Org.OpenTrader.Framework.Forge.DataCache;
    using Org.OpenTrader.Framework.Forge.Enums;
    using Org.OpenTrader.Framework.Forge.Interfaces;
    using Org.OpenTrader.Framework.LiveObjects;
    using Org.OpenTrader.Framework.LiveObjects.Interfaces;

    #endregion

    /// <summary>
    /// The dictionary service.
    /// </summary>
    [Credits("Dictionary Service", "Registry of all instruments", "David Denis", "Copyright (C) David Denis <mailto:david.denis@systemathics.com>")]
    [ImplementsInterface("Org.OpenTrader.Framework.Forge.Interfaces.IDictionaryService")]
    public sealed class DictionaryService : Service, IDictionaryService
    {
        #region Constants and Fields

        /// <summary>
        /// The identity.
        /// </summary>
        private static readonly Identity Identity = Identity.Create(MethodBase.GetCurrentMethod());

        #endregion

        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="DictionaryService"/> class.
        /// </summary>
        /// <param name="descriptor">
        /// The descriptor.
        /// </param>
        /// <param name="container">
        /// The container.
        /// </param>
        public DictionaryService(ILiveObjectDescriptor descriptor, ILiveObjectContainer container)
            : base(descriptor, container)
        {
        }

        #endregion

        #region Implemented Interfaces

        #region IDictionaryProvider

        /// <summary>
        /// The lookup instrument.
        /// </summary>
        /// <param name="code">
        /// The code.
        /// </param>
        /// <param name="tradingScope">
        /// The tradingScope.
        /// </param>
        /// <typeparam name="T">
        /// </typeparam>
        /// <returns>
        /// </returns>
        public Status<T> LookupInstrument<T>(string code, ETradingScope tradingScope) where T : IInstrumentStaticData
        {
            try
            {
                var instruments = from i in Singleton<DC>.Instance.GetInstrumentsStaticDataFromCache(this.Descriptor.ID)
                                  where i.Code == code
                                  where i.TradingScope == tradingScope
                                  select i;

                if (instruments.Count() == 1)
                {
                    var data = instruments.First();
                    return Status.Success<T>(Identity, (T)data);
                }
                else if (instruments.Count() > 1)
                {
                    return Status.Failure<T>(Identity, "CreateInstrument: More than 1 match");
                }
                else
                {
                    return Status.Failure<T>(Identity, "CreateInstrument: No match");
                }
            }
            catch (Exception e)
            {
                return Status.Failure<T>(Identity, string.Format("CreateInstrument: Got exception {0}", e));
            }
        }

        /// <summary>
        /// The lookup instruments.
        /// </summary>
        /// <param name="predicate">
        /// The predicate.
        /// </param>
        /// <returns>
        /// </returns>
        public Status<IInstrumentStaticData[]> LookupInstruments(Expression<Func<IInstrumentStaticData, bool>> predicate)
        {
            try
            {
                var instruments = Singleton<DC>.Instance.GetInstrumentsStaticDataFromCache(this.Descriptor.ID).AsQueryable().Where(predicate.Compile());

                return Status.Success<IInstrumentStaticData[]>(Identity, instruments.ToArray());
            }
            catch (Exception e)
            {
                return Status.Failure<IInstrumentStaticData[]>(Identity, string.Format("CreateInstruments: Got exception {0}", e));
            }
        }

        /// <summary>
        /// The lookup markets.
        /// </summary>
        /// <param name="predicate">
        /// The predicate.
        /// </param>
        /// <returns>
        /// </returns>
        public Status<IMarket[]> LookupMarkets(Expression<Func<IMarket, bool>> predicate)
        {
            try
            {
                var markets = Singleton<DC>.Instance.GetMarketsFromCache(this.Descriptor.ID).AsQueryable().Where(predicate.Compile());

                return Status.Success<IMarket[]>(Identity, markets.ToArray());
            }
            catch (Exception e)
            {
                return Status.Failure<IMarket[]>(Identity, string.Format("LookupMarkets: Got exception {0}", e));
            }
        }

        #endregion

        #region ILiveObject

        /// <summary>
        /// The on activation context.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="activationEventArgs">
        /// The activation Context.
        /// </param>
        public override void OnActivation(object sender, ActivationEventArgs activationEventArgs)
        {
            if (activationEventArgs is ActivationEventArgs.CreateDestroy)
            {
                var createdestroyArgs = activationEventArgs as ActivationEventArgs.CreateDestroy;
                switch (createdestroyArgs.Type)
                {
                    case EActivationType.Activation:

                        // The dictionary ID is the same as this service ID for convenience
                        var dictionaryId = this.Descriptor.ID;

                        // Create a dictionary if not already there
                        if (!Singleton<DC>.Instance.ExistsDictionary(dictionaryId))
                        {
                            Singleton<DC>.Instance.CreateDictionary(dictionaryId, ECurrency.EUR);
                        }

                        break;

                    case EActivationType.Desactivation:
                        break;
                }
            }
        }

        #endregion

        #endregion
    }
}